package code.homework;

import java.util.Stack;

/**
 * @author cc
 * @create 2023-01-18  22:21
 */
public class AsteroidCollision {

    /**
     *  [5,10,-5]
     *   [5]
     *   [10,5]
     *   [10,5]
     *
     *   [-10,20,5]
     *   [-10]
     *   [5,20]
     *
     *   注意用例 [-2,-1,1,2] 输出是 [-2,-1,1,2]
     *   +-会碰撞
     *   -+不会
     */
    public static int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();
        for (int i:asteroids){
            if(stack.isEmpty()) {
                stack.push(i);
                continue;
            }
            Integer peek ;
            boolean isNeedAdd = true;
            while( !stack.isEmpty() && (((peek=stack.peek()) > 0 && i < 0))) {
                if(peek + i == 0) {
                    stack.pop();
                    isNeedAdd = false;
                    break;
                } else if (Math.abs(peek) > Math.abs(i)) {
                    isNeedAdd = false;
                    break;
                } else {
                    stack.pop();
                    isNeedAdd = true;
                }
            }
            if(isNeedAdd) {
                stack.push(i);
            }

        }
        int[] result = new int[stack.size()];
        int j = 0;
        for(Integer num : stack) {
            result[j] = num;
            j++;
        }
        return result;
    }

    public static void main(String[] args) {
        int[] ints = {5,10,-5};
        asteroidCollision(ints);
    }
}
